<?php
/**
 * User: @lixu
 * Date: 2019-02-18
 * Time: 15:28
 */

namespace Biz\service\activity;

use Biz\cache\activity\PinTuan as cPinTuan;
use Biz\model\activity\PinTuan as mPinTuan;
use Biz\model\activity\PinTuanSku as mPinTuanSku;
use Biz\model\trade\GroupJoin as mGroupJoin;
use Biz\model\trade\GroupJoinMember as mGroupJoinMember;
use Biz\module\Classes\adm\PinTuan as admPinTuan;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\Goods as sGoods;
use Biz\service\Group as sGroup;
use Biz\service\Sku;
use Doraemon\pockets\constInterface\AppType;
use Doraemon\service\User;

/**
 * @deprecated
 */
class PinTuan implements AppType, ActivityInfo
{
    const LIST_COUNT = 9;

    public static function admGetPinTuanList($params = [])
    {
        $list = admPinTuan::getPinTuanList($params);

        return ['list' => $list['list'], 'total' => $list['total']];
    }

    public static function admGetPinTuanSkuList($params = [])
    {
        $list = admPinTuan::getPinTuanSkuList($params);
        return ['list' => $list['list'], 'total' => $list['total']];
    }

    public static function Goods($goodsId, $cityId, $uid, $appType)
    {
        $goodsInfo = sGoods::Goods($goodsId, sGoods::FIELDS_GROUP_DETAIL, ['redundancy_type' => self::ACTIVITY_TYPE_PINTUAN, 'not_activity_type' =>[self::ACTIVITY_TYPE_PINTUAN], 'area_code' => $cityId], $uid);
        $goodsInfo['teams_count'] = mGroupJoin::getCreateCount($uid);
        $team = self::getCurrentList([$goodsId]);
        if ($appType && $appType == self::APPTYPE_MINIPROGRAM) {
            $recommends = self::recommendGoods($goodsId);
            $goodsInfo = array_merge($goodsInfo, ['recommend_goods' => $recommends]);
        }
        $skuIds = array_column($team[$goodsId]['skus'], 'sku_id');
        $skuList = Sku::Sku4Order($skuIds);
        $actualStock = 0;
        $pintuanSkus = array_column($team[$goodsId]['skus'], 'sku_id');
        foreach ($skuList as $skuId => $skuInfo) {
            if (in_array($skuId, $pintuanSkus) && isset($skuInfo['actual_stock'])) {
                $actualStock = $actualStock + $skuInfo['actual_stock'];
            }
        }
        $goodsInfo = array_merge($goodsInfo, ['recommend_goods' => $recommends]);
        $goodsInfo = array_merge($goodsInfo, ['actual_stock' => $actualStock]);
        $goodsInfo = array_merge($goodsInfo, ['activity_stock' =>  array_sum( array_column($team[$goodsId]['skus'], 'actual_stock') )]);
        $goodsInfo = array_merge($goodsInfo, ['more_teams' => sGroup::goodsDetail($goodsId)]);

        return $goodsInfo;

    }

    public static function recommendGoods($goodsId)
    {
        $teamsinfos = mPinTuansku::otherGoodsInfos($goodsId);
        $recommendList = [];
        if ($teamsinfos) {
            $goodsList = sGoods::Goods(array_keys($teamsinfos), sGoods::FIELDS_GROUP_LIST, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_PINTUAN]);
            $teamInfo = sGroup::team_info(array_keys($teamsinfos));
            foreach ($teamsinfos as $goodsId => $teamskus) {
                if ($teamInfo[$goodsId]['max_price']
                    && $teamInfo[$goodsId]['min_price']
                    && $goodsList[$goodsId]['actual_stock']
                    && $goodsList[$goodsId]['activity_stock'] //拥有活动库存和实际库存
                ) {
                    $goodsList[$goodsId]['ori_min_price'] = $teamInfo[$goodsId]['ori_min_price'];
                    $goodsList[$goodsId]['ori_max_price'] = $teamInfo[$goodsId]['ori_max_price'];
                    $goodsList[$goodsId]['actual_min_price'] = $teamInfo[$goodsId]['min_price'];
                    $goodsList[$goodsId]['actual_max_price'] = $teamInfo[$goodsId]['max_price'];
                    $recommendList[] = $goodsList[$goodsId];
                }
            }
        }
        return $recommendList;
    }


    public static function getCurrentList(array $goodsIds, $checkDate = true)
    {
        $results = [];
        $currentTime = date('Y-m-d H:i:s');
        $pintuanList = self::getPintuanList($goodsIds);
        foreach ($pintuanList as $goodsId => $item) {
            if ($checkDate) {
                if ($item && $item['start_time'] < $currentTime && $item['end_time'] > $currentTime) {
                    $results[$goodsId] = $item;
                }
            } else {
                $results[$goodsId] = $item;
            }
        }
        return $results;
    }

    public static function getPintuanList(array $goodsIds)
    {
        list($cacheData, $goodsIds) = cPinTuan::pHGetAllItems($goodsIds);

        if ($goodsIds) {
            $list = self::getPintuansInDb($goodsIds);
            $cacheData = $cacheData + $list;
            $cachedData = [];
            foreach ($goodsIds as $goodsId) {
                $cachedData[$goodsId] = isset($list[$goodsId]) ? $list[$goodsId] : [0];
            }
            cPinTuan::setItems($cachedData);
        }

        foreach ($cacheData as $goodsId => $teamInfo) {
            $cacheData[$goodsId] = array_filter($teamInfo);
            if ($cacheData[$goodsId]) {
                mPinTuan::formatInfo($teamInfo);
                $prices = $teamInfo['skus'] ? array_column($teamInfo['skus'], 'activity_price') : [];
                $stocks = $teamInfo['skus'] ? array_column($teamInfo['skus'], 'actual_stock') : [];
                $cacheData[$goodsId] = array_merge($teamInfo, [
                    'min_price' => $prices ? min($prices) : 0.00,
                    'max_price' => $prices ? max($prices) : 0.00,
                    'actual_stock' => array_sum($stocks),
                    'time_down' => [
                        'sys_time' => time(),
                        'begin_time' => strtotime($teamInfo['start_time']),
                        'end_time' => strtotime($teamInfo['end_time']),
                    ]
                ]);
            }
        }

        return $cacheData;

    }

    private static function getPintuansInDb($goodsIds)
    {
        $list = mPinTuan::getNotOverInfosByGid($goodsIds);
        $pintuanIds = array_column($list, 'id');
        $skusGrpById = mPinTuanSku::getListByTeamId($pintuanIds);

        foreach ($list as $goodsId => $item) {
            $list[$goodsId]['expire'] = self::expire($item['start_time'], $item['end_time']);
            $list[$goodsId]['skus'] = $skusGrpById[$item['id']];
        }

        return $list;
    }

    private static function expire($startTime, $endTime)
    {
        $startTimeStamp = strtotime($startTime);
        $endTimeStamp = strtotime($endTime);
        if ($startTimeStamp < time()) {
            $expire = $endTimeStamp - time();
        } else {
            $expire = $startTimeStamp - time();
        }
        return $expire;
    }


    public static function admGetPinTuanInfo($id)
    {
        return mPinTuan::getInfo(['id' => $id, 'status' => mPinTuan::STATUS_NORMAL]);
    }

    public static function admGetPinTuanSkuInfo($pinTuanSkuId)
    {
        return admPinTuan::getPinTuanSkuInfo($pinTuanSkuId);
    }

    public static function admSavePinTuan($id, $goodsId, $list, $adminId)
    {
        return admPinTuan::savePinTuan($id, $goodsId, $list, $adminId);
    }

    public static function admAddPinTuanSku($id, $sku, $adminId)
    {
        return admPinTuan::addPinTuanSku($id, $sku, $adminId);
    }

    public static function admGetSkuList($id)
    {
        return admPinTuan::getSkuList($id);
    }

    public static function admSaveSku($id, $pinTuanSkuId, $param)
    {
        return admPinTuan::saveSku($id, $pinTuanSkuId, $param);
    }

    public static function admDelPinTuan($id, $adminId)
    {
        return admPinTuan::delPinTuan($id, $adminId);
    }

    public static function admDelPinTuanSku($id, $pinTuanSkuId)
    {
        return admPinTuan::delPinTuanSku($id, $pinTuanSkuId);
    }

    /**
     * 获取拼团状态
     * $activity array 活动的id=>order_no
     **/
    public static function getOrder($activity = '')
    {
        $data = [];
        $pintuanSku = mGroupJoinMember::select(
            '*',
            !empty($activity) ? ['order_no' => array_values($activity),'status[!]'=>[mGroupJoin::STATUS_WAIT_PAY, mGroupJoin::STATUS_DEL]] : ''
        );

        if (isset($pintuanSku)) {
            $group_join_id = array_column($pintuanSku, 'group_join_id');
            $pintuan = mGroupJoin::select(
                '*',
                !empty($group_join_id) ? ['id' => $group_join_id] : ''
            );

            $group_id = array_column($pintuanSku, 'group_id');
            $pintuanGoods = mPinTuan::getList(['id' => $group_id], ['id', 'type', 'cover_img']);
            $pintuanGoods = array_column($pintuanGoods, NULL, 'id');

            //获取最高价和最低价
            $pintuanSkus = mPinTuanSku::getList(['pintuan_id' => $group_id,'activity_price[>]'=>0, 'status'=>mPinTuanSku::STATUS_NORMAL]);
            foreach($pintuanSkus as $_psk=>&$_psv){
                $pintuanList[$_psv['pintuan_id']][$_psv['goods_id']][$_psv['sku_id']] = $_psv['activity_price'];
            }

            //获取团长图像
            $uid = array_column($pintuan, 'uid');
            $user = User::getUsers($uid);

            foreach ($pintuan as $_k => &$_v) {
                foreach ($pintuanSku as $_sk => &$_sv) {
                    if ($_sv['group_join_id'] == $_v['id']) {
                        switch ($_v['reason']) {
                            case 1:
                                $_v['reason_descrip'] = '很遗憾，拼的有点慢，商品已被抢光';//真实库存已为0
                                break;
                            case 2:
                                $_v['reason_descrip'] = '很遗憾，超时未凑齐好友';//超时未凑够人数
                                break;
                            default:
                                $_v['reason_descrip'] = '';
                                break;
                        }
                        //获取参团状态来源于join_member
                        $_v['status'] = $_sv['status'];
                        switch ($_v['status']) {
                            case 0:
                                $_v['status_descrip'] = '未开团';
                                break;
                            case 1:
                                $_v['status_descrip'] = '拼团中';
                                break;
                            case 2:
                                $_v['status_descrip'] = '拼团成功';
                                break;
                            case 3:
                                $_v['status_descrip'] = '拼团失败';
                                break;
                            case 4:
                                $_v['status'] = 3;
                                $_v['status_descrip'] = '拼团失败';
                                break;
                            case 9:
                                $_v['status_descrip'] = '取消拼团';
                                break;
                        }
                        $data[$_sv['order_no']] = $_v;
                        $data[$_sv['order_no']]['not_join_member'] = $_v['member'] - $_v['join_member'];
                        $data[$_sv['order_no']]['sku'][$_sv['sku_id']] = $_sv;
                        $data[$_sv['order_no']]['user'] = $user[$_v['uid']];

                        if(isset($pintuanList[$_v['group_id']][$_v['goods_id']])){
                            $data[$_sv['order_no']]['min_price'] = min($pintuanList[$_v['group_id']][$_v['goods_id']]);
                            $data[$_sv['order_no']]['max_price'] = max($pintuanList[$_v['group_id']][$_v['goods_id']]);
                        }else{
                            $data[$_sv['order_no']]['min_price'] = 0;
                            $data[$_sv['order_no']]['max_price'] = 0;
                        }

                        if (isset($pintuanGoods) && $pintuanGoods[$_v['group_id']]) {
                            $data[$_sv['order_no']]['type_descrip'] = $pintuanGoods[$_v['group_id']]['type_desc'];
                            $data[$_sv['order_no']]['cover_img_url'] = $pintuanGoods[$_v['group_id']]['cover_img_url'];
                        }else{
                            $data[$_sv['order_no']]['type_descrip'] = '';
                            $data[$_sv['order_no']]['cover_img_url'] = '';
                        }

                    }
                }
            }
        }

        return $data;
    }

    /**
     * 获取拼团订单商品信息和状态
     * $activity array 活动的id
     **/
    public static function getSkuOrder($activity = '', $skuList = '')
    {
        $data = [];
        if (!empty($skuList)) {
            $activityData = self::getOrder($activity);
            foreach ($skuList as $_sk => &$_sv) {
                if (isset($activityData[$_sv['order_no']])) {
                    $pintuan = $activityData[$_sv['order_no']];
                    $pintuanSku = $activityData[$_sv['order_no']]['sku'][$_sv['sku_id']];
                    if($pintuanSku['sku_id'] == $_sv['sku_id']) {
                        //开团
                        $data['team_info'][$_sv['order_no']] = [
                            'activity_id'=> $pintuan['group_id'],
                            'activity_icon'=> $pintuan['cover_img_url'],
                            'min_price'=> $pintuan['min_price'],
                            'max_price'=> $pintuan['max_price'],
                        ];
                        //参团
                        $data['team_join_info'][$_sv['order_no']] = [
                            'team_join_id' => $pintuan['id'],
                            'team_join_status'=> $pintuan['status'],
                            'team_join_status_desc'=> $pintuan['status_descrip'],
                            'goods_id'=> $pintuan['goods_id'],
                            'group_buy_price'=> $pintuan['group_buy_price'],
                            'group_member_num'=> $pintuan['member'],
                            'last_member_num' => $pintuan['not_join_member'],
                            'fail_reason_desc'=> $pintuan['reason_descrip'],
                            'users'=> [
                                'nick'=> $pintuan['user']['nick'],
                                'avatar'=> $pintuan['user']['avatar'],
                                'team_leader' => $pintuan['type']
                            ],
                            'time_down'=> [
                                'sys_time'=> time(),
                                'begin_time'=> strtotime($pintuan['start_time']),
                                'end_time'=> strtotime($pintuan['end_time']),
                            ],
                        ];
                        //activity的图标
                        $data[$_sv['order_no']] = [
                            'active_icon_list'=> [$pintuan['cover_img_url']]
                        ];

                    }
                    unset($pintuan,$pintuanSku);
                }
            }
        }
        return $data;
    }

    /**
     * 拼团列表页
     * @param string $count
     * @return array
     */
    public static function getList($count = '*')
    {
        $effectiveList = [];
        $invalidList = [];
        $where['AND'] = [
            'status' => mPinTuan::STATUS_NORMAL,
            'start_time[<=]' => date('Y-m-d H:i:s'),
            'end_time[>=]' => date('Y-m-d H:i:s'),
        ];
        $where['ORDER'] = ['sort' => 'DESC', 'start_time' => 'DESC', 'id' => 'DESC'];
        $pinTuanList = mPinTuan::getList($where, ['id', 'goods_id', 'cover_img', 'group_member_num']);

        $goodsIds = array_column($pinTuanList, 'goods_id');

//        // 取到了拼团的最低价和最高价 以及参与了拼团的sku
//        $list = self::getPintuanList($goodsIds);
//        foreach ($list as $goodsId => $info) {
//            if($info['min_price'] && $info['max_price']) {
//                $activityPriceList[$goodsId] = [
//                    'min_price' => $info['min_price'],
//                    'max_price' => $info['max_price'],
//                ];
//            }
//            foreach ($info['skus'] as $sku) {
//                $skuIdList[$goodsId][] = $sku['sku_id'];
//            }
//        }

//        // 取出参与了拼团的sku的原价
//        $skuInfos = sSku::sku($goodsIds, sSku::FIELDS_GROUP_ALL, ['not_activity_type' => [self::ACTIVITY_TYPE_PINTUAN]]);
//        $price = [];
//        $stock = [];
//        foreach ($skuInfos as $goodsId => $sku) {
//            foreach ($sku['sku_info'] as $item) {
//                if(in_array($item['sku_id'], $skuIdList[$goodsId])) {
//                    $price[$goodsId][] = $item['actual_price'];
//                    $stock[$goodsId] += $sku[sSku::FIELDS_GROUP_BASE]['goods_stock'][$item['sku_id']];
//                }
//            }
//            $oriPriceList[$goodsId] = [
//                'min_price' => min($price[$goodsId]),
//                'max_price' => max($price[$goodsId]),
//                'stock' => $stock[$goodsId],
//            ];
//        }


        $pinTuanGoodsInfo = sGoods::goods($goodsIds, sGoods::FIELDS_GROUP_LIST, ['activity_type' =>self::ACTIVITY_TYPE_PINTUAN]);

        $teamInfo = sGroup::team_info($goodsIds);

        $teamInfo = array_map(function ($info){
            $info['stock'] = array_sum(array_column($info['sku_stock'], 'stock'));
            return $info;
        }, $teamInfo);

        foreach ($pinTuanList as $info) {
            $goodsId = $info['goods_id'];
            if(isset($pinTuanGoodsInfo[$goodsId])) {
                if(($pinTuanGoodsInfo[$goodsId]['activity_stock'] && $pinTuanGoodsInfo[$goodsId]['activity_stock'] >= $info['group_member_num'])  && ($teamInfo[$goodsId]['stock'] && $teamInfo[$goodsId]['stock'] >= $info['group_member_num']) && $teamInfo[$goodsId]['activity_status'] == 1) {
                    $effectiveList[] = [
                        'id' => $goodsId,
                        'title' => $pinTuanGoodsInfo[$goodsId]['title'],
                        'cover_img' => $pinTuanGoodsInfo[$goodsId]['cover_img'],
                        'ori_min_price' => $teamInfo[$goodsId]['ori_min_price'],
                        'ori_max_price' => $teamInfo[$goodsId]['ori_max_price'],
                        'actual_min_price' => $teamInfo[$goodsId]['min_price'],
                        'actual_max_price' => $teamInfo[$goodsId]['max_price'],
                        'actual_stock' => $teamInfo[$goodsId]['stock'],
                        'activity_stock' => $pinTuanGoodsInfo[$goodsId]['activity_stock'],
                        'active_icon_list' => $pinTuanGoodsInfo[$goodsId]['active_icon_list'],
                        'group_member_num' => $info['group_member_num'],
                        'activity_type' => $pinTuanGoodsInfo[$goodsId]['activity_type'],
                        'activity_status' => $teamInfo[$goodsId]['activity_status'],
                    ];
                } else {
                    $invalidList[] = [
                        'id' => $goodsId,
                        'title' => $pinTuanGoodsInfo[$goodsId]['title'],
                        'cover_img' => $pinTuanGoodsInfo[$goodsId]['cover_img'],
                        'ori_min_price' => $teamInfo[$goodsId]['ori_min_price'],
                        'ori_max_price' => $teamInfo[$goodsId]['ori_max_price'],
                        'actual_min_price' => $teamInfo[$goodsId]['min_price'],
                        'actual_max_price' => $teamInfo[$goodsId]['max_price'],
                        'actual_stock' => $teamInfo[$goodsId]['stock'],
                        'activity_stock' => $pinTuanGoodsInfo[$goodsId]['activity_stock'],
                        'active_icon_list' => $pinTuanGoodsInfo[$goodsId]['active_icon_list'],
                        'group_member_num' => $info['group_member_num'],
                        'activity_type' => $pinTuanGoodsInfo[$goodsId]['activity_type'],
                        'activity_status' => $teamInfo[$goodsId]['activity_status'],
                    ];
                }
            }
        }

        $list = array_merge($effectiveList, $invalidList);
        if($count == self::LIST_COUNT) {
            $list = array_slice($list, 0, self::LIST_COUNT);
        }
        return $list ? : [];
    }


    public static function getListActivityRegister($goodsIds, $stopTime)
    {
        $startTime = date('Y-m-d H:i:s', strtotime($stopTime) + (86400 * 5));
        $goodsIds = explode(',', $goodsIds);
        $where = [
            'goods_id' => $goodsIds,
            'start_time[<=]' =>$startTime,
            'end_time[>=]' => $stopTime,
            'status' => mPinTuan::STATUS_NORMAL
        ];
        $info = mPinTuan::getList($where);

        $pinTuanIds = array_column($info, 'id');
        $list = mPinTuanSku::getListByTeamId($pinTuanIds);
        $tips = [];
        foreach ($info as $value) {
            $activityPrice = array_column($list[$value['id']], 'activity_price');
            $minPrice = min($activityPrice);
            $maxPrice = max($activityPrice);
            $tips[] = "商品:" .$value['goods_id'] . " 参与了拼团 " . "拼团ID:" . $value['id'] . " 时间范围:" . $value['start_time'] . ' ~ ' . $value['end_time'] . ' 价格范围:' . $minPrice . '-' . $maxPrice;
        }
        return $tips;
    }

}